#include "InSdkSaveLastDate.h"

#define DEF_TAG "SaveDate"

#define DEF_SAVE_LAST_TIME (5 * 60)

Com_void InSdkSaveDate_SetTime(Com_void)
{
    int ret;
    char buf[24];
    time_t save_time;
    struct tm mk_time;
    struct timeval set_time;
    StComCurrentTime save_date;

    memset(buf, 0, sizeof(buf));
    memset(&mk_time, 0, sizeof(mk_time));
    memset(&set_time, 0, sizeof(set_time));
    memset(&save_time, 0, sizeof(save_time));
    memset(&save_date, 0, sizeof(save_date));

    Ext_InComFile_ReadStr(DEF_TXT_SAVE_LAST_DATE, buf, sizeof(buf));
    PRT_INFO(DEF_TAG, "get file date: %s\n", buf);

    sscanf(buf, "%d-%d-%d %d:%d:%d", &save_date.year, &save_date.mon, &save_date.day,
           &save_date.hour, &save_date.min, &save_date.sec);
    mk_time.tm_year = save_date.year - 1900;
    mk_time.tm_mon = save_date.mon - 1;
    mk_time.tm_mday = save_date.day;
    mk_time.tm_hour = save_date.hour;
    mk_time.tm_min = save_date.min;
    mk_time.tm_sec = save_date.sec;

    save_time = mktime(&mk_time);
    set_time.tv_sec = save_time;
    ret = settimeofday(&set_time, NULL);
    if (ret < 0)
    {
        perror("settimeofday failed");
    }

    return;
}

Com_void InSdkSaveDate_GetTime(Com_void)
{
    time_t currTime;
    char date_str[24];
    struct tm *currDate = NULL;

    memset(date_str, 0, sizeof(date_str));
    memset(&currTime, 0, sizeof(currTime));

    time(&currTime);
    currDate = localtime(&currTime);
    strftime(date_str, sizeof(date_str), "%Y-%m-%d %H:%M:%S", currDate);
    PRT_INFO(DEF_TAG, "save date: %s\n", date_str);
    Ext_InComFile_Write(DEF_TXT_SAVE_LAST_DATE, date_str, sizeof(date_str));

    return;
}

void *InSdkSaveDate_Thread(void *arg)
{
    if (Ext_InComFile_Access(DEF_FLAG_NO_NETWORK) == DEF_COM_FILE_EXIST)
    {
        Ext_InComFile_Remove(DEF_TXT_SAVE_LAST_DATE);
    }

    if (Ext_InComFile_Access(DEF_TXT_SAVE_LAST_DATE) == 0)
    {
        InSdkSaveDate_SetTime();
    }

    while (Ext_InComFile_Access(DEF_FLAG_SYNC_TIME_OK) == DEF_COM_FILE_NOT_EXIST)
    {
        sleep(1);
    }

    while (g_ComThread_Running)
    {
        InSdkSaveDate_GetTime();
        sleep(DEF_SAVE_LAST_TIME);
    }

    pthread_exit(0);
}

Com_void Ext_InSdkSaveDate_Init(Com_void)
{
    pthread_t id;

    pthread_create(&id, NULL, InSdkSaveDate_Thread, NULL);
    pthread_detach(id);
}
